package cn.xnatural.demo.service;

import cn.xnatural.app.Bean;
import cn.xnatural.app.Inject;
import cn.xnatural.app.ServerTpl;
import cn.xnatural.app.Utils;
import cn.xnatural.enet.event.EL;
import cn.xnatural.demo.entity.Test;
import cn.xnatural.demo.entity.User;
import cn.xnatural.jpa.Page;
import cn.xnatural.jpa.Repo;

import java.text.SimpleDateFormat;
import java.util.Date;

@Bean
public class TestService extends ServerTpl {

    @Inject Repo repo;



    @EL(name = "sys.starting", async = true)
    void starting() {
        log.info("{} starting...", name);
    }

    @EL(name = "sys.started", async = true)
    void started() {
        log.info("{} started...", name);

        log.info("=========" + repo.count(User.class));

        String s = Utils.http("http://localhost:7070/test/cus").get();
        log.info("==========" + s);
    }



    @EL(name = "sys.heartbeat", async = true)
    void timeNotify() {
        // 向测试 web socket 每分钟发送消息
        ep.fire("testWsMsg", "系统时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }


    @EL(name = "eName1")
    String testEvent1(String p) {
        Test e = new Test();
        e.setName("aaaa" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        e.setAge(111);
        Test t = bean(Repo.class).saveOrUpdate(e);
        // if (true) throw new IllegalArgumentException("xxx");
        return "new entity : " + t.getId();
    }


    @EL(name = "eName2")
    Page<Test> testEvent2(String p) {
        return bean(Repo.class).paging(Test.class, 1, 10, (root, query, cb) -> query.orderBy(cb.desc(root.get("id"))));
    }


    @EL(name = "eName3")
    long testEvent3(String p) {
        return bean(Repo.class).count(Test.class);
    }


    @EL(name = "testevent.cus")
    Object cus(Object p) { return p; }


    @EL(name = "testevent.jpa")
    long jpa() { return repo.count(Test.class); }


    @EL(name = "testevent.error")
    Object error(String p) {
        throw new RuntimeException("抛个错 " + p);
    }

    @EL(name = "testevent.timeout")
    void timeout(Long wait) throws Exception {
        Thread.sleep(wait == null || wait < 0 ? 1 : wait);
    }
}
